import requests
import json
import time
import random
import pandas as pd

# 配置信息
BASE_URL = 'http://129.1.0.16/api/partner/suggest/grouping'
REFERER = 'http://129.1.0.16/clinic?token=d67e3defbbd74a1f8164c2b7442c253b'
ORIGIN = 'http://129.1.0.16'

# 定义一个User-Agent池
user_agent_pool = [
    # Chrome
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    # Edge
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59",
]

# 请求头
HEADERS = {
    'User-Agent': random.choice(user_agent_pool),
    'Referer': REFERER,
    'Origin': ORIGIN,
    'Content-Type': 'application/json; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
}

#所有入参
df = pd.read_excel('JZ_PRAR.xlsx', header=None)

# 初始请求参数
PARAMS = {
    "token":"d67e3defbbd74a1f8164c2b7442c253b",
    "ageType":"1",
    "age":0,
    "hospitalTime":0,
    "leaveHospitalType":"6",
    "mainDiagnoseCode":"",
    "mainDiagnoseName":"",
    "mainOperCode":"",
    "mainOperName":"",
	"otherDiagnoses":[],
    "otherOpers": []
}

REPONSE = {
    'rows_key': 'data'
}

# 为了避免触发反爬虫机制，等待 3.4秒,亲测访问频率低于0.3333...,即10秒内请求小于等于3次
sleep_seconds = 0.5

# 保存所有数据的列表
all_items = []

def fetch_data(session, params):
    """发送 POST 请求并返回 JSON 数据"""
    try:
        response = session.post(BASE_URL, data=params, headers=HEADERS)
        response.raise_for_status()  # 检查请求是否成功	
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None

def main():
    # 创建一个会话对象，自动管理 Cookie
    session = requests.Session()

    for index, row in df.iterrows():
        if index == 0:
            continue
        params = PARAMS.copy()
        params['mainDiagnoseCode'] = row[0]
        params['mainDiagnoseName'] = row[1]
        if pd.isna(row[2]):
            params['mainOperCode'] = ''
            params['mainOperName'] = ''
            params['otherOpers'] = []
        elif ',' in row[2]:
            opsList = row[2].split(',')
            opsNameList = row[3].split(',')
            params['mainOperCode'] = opsList.pop(0)
            params['mainOperName'] = opsNameList.pop(0)
            #row = # 分割字符串为列表
            codes = [code.strip() for code in opsList]
            names = [name.strip() for name in opsNameList]
            # 构建 otherOpers 列表
            params['otherOpers'] = [
                {
                    "code": code,
                    "name": name,
                    "content": f"{code}|{name}"
                }
                for code, name in zip(codes, names)
            ]
        else:
            params['mainOperCode'] = row[2]
            params['mainOperName'] = row[3]
            params['otherOpers'] = []
        # 获取当前页的数据
        print(f"参数：{params}")
        data = fetch_data(session, params)
        # 获取当前页的数据
        items = data.get(REPONSE['rows_key'], [])

        # 将当前页的数据添加到总列表中
        all_items.extend(items)
        print(f"返回：{items}")
        print(f"行号：{index+1}，获取数据数量{len(items)}")

        time.sleep(sleep_seconds)

    # 保存所有数据到 JSON 文件
    with open('cat.json', 'w', encoding='utf-8') as f:
        json.dump(all_items, f, ensure_ascii=False, indent=4)

    print(f"已保存到 cat.json 文件中。")

if __name__ == "__main__":
    main()